//
//  LoginViewController.m
//  ChengXinBao
//
//  Created by RongZhou on 17/3/6.
//  Copyright © 2017年 RongZhou. All rights reserved.
//

#import "LoginViewController.h"
#import <AFNetworking.h>
#import <Masonry.h>
#import "RegisterViewController.h"
@interface LoginViewController ()<UITextFieldDelegate>

@property(nonatomic,strong)UITextField *userTextfiled;
@property(nonatomic,strong)UITextField *passwordTextfiled;
@property(nonatomic,strong)UIButton *remeberbutton;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.view.backgroundColor = [UIColor whiteColor];
//    http://localhost:8080/phoneUserApp/savePhoneUser?phone=13764955526&passWord=123456&name=爱大米
    [self createloginView];
    UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissTheLogin:)];
    [self.view addGestureRecognizer:swip];
}
-(void)dismissTheLogin:(UISwipeGestureRecognizer *)swip{
    if (swip.direction == UISwipeGestureRecognizerDirectionRight) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    if (swip.direction == UISwipeGestureRecognizerDirectionLeft) {
        [self registerNewAcount];
    }
}
-(void)viewWillAppear:(BOOL)animated{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]) {
        [_remeberbutton setImage:[UIImage imageNamed:@"Login03"] forState:UIControlStateNormal];
        _userTextfiled.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
        _passwordTextfiled.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"passWord"];
    }else{
        [_remeberbutton setImage:[UIImage imageNamed:@"Login02"] forState:UIControlStateNormal];
    }
}
/**
 *  页面布局
 */
-(void)createloginView{
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    bgImageView.image = [UIImage imageNamed:@"loginBg"];
    [self.view addSubview:bgImageView];
    [self.view insertSubview:bgImageView atIndex:0];
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"诚信宝";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(64);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.height.mas_equalTo(50);
    }];
    UIView *topView = [[UIView alloc] init];
    topView.backgroundColor = [UIColor whiteColor];
    topView.layer.cornerRadius = 30;
    topView.layer.masksToBounds = YES;
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_top).offset(30 + 64);
        make.right.equalTo(self.view.mas_right).offset(-30);
        make.left.equalTo(self.view.mas_left).offset(30);
        make.height.mas_equalTo(60);
    }];
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = [UIColor whiteColor];
    bottomView.layer.cornerRadius = 30;
    bottomView.layer.masksToBounds = YES;
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-30);
        make.left.equalTo(self.view.mas_left).offset(30);
        make.height.mas_equalTo(60);
    }];
    UIImageView *topImageView = [[UIImageView alloc] init];
    topImageView.image = [UIImage imageNamed:@"tab_username"];
    [topView addSubview:topImageView];
    [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(topView.mas_centerY);
        make.height.mas_equalTo(32);
        make.width.mas_equalTo(32);
        make.left.equalTo(topView.mas_left).offset(10);
    }];
    UIImageView *bottomImageView = [[UIImageView alloc] init];
    bottomImageView.image = [UIImage imageNamed:@"tab_password"];
    [bottomView addSubview:bottomImageView];
    [bottomImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bottomView.mas_centerY);
        make.height.mas_equalTo(32);
        make.width.mas_equalTo(32);
        make.left.equalTo(bottomView.mas_left).offset(10);
    }];
    _userTextfiled = [[UITextField alloc] init];
    [topView addSubview:_userTextfiled];
    _userTextfiled.placeholder = @"请输入手机号";
    _userTextfiled.delegate = self;
    [_userTextfiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_top).offset(10);
        make.bottom.equalTo(topView.mas_bottom).offset(-10);
        make.right.equalTo(topView.mas_right).offset(-10);
        make.left.equalTo(topImageView.mas_right).offset(10);
    }];
    _passwordTextfiled = [[UITextField alloc] init];
    [bottomView addSubview:_passwordTextfiled];
    _passwordTextfiled.placeholder = @"密码";
    _passwordTextfiled.delegate = self;
    [_passwordTextfiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomView.mas_top).offset(10);
        make.bottom.equalTo(bottomView.mas_bottom).offset(-10);
        make.right.equalTo(bottomView.mas_right).offset(-10);
        make.left.equalTo(bottomImageView.mas_right).offset(10);
    }];
    
    _remeberbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_remeberbutton setTitle:@"  记住密码" forState:UIControlStateNormal];
    [_remeberbutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_remeberbutton setImage:[UIImage imageNamed:@"Login02"] forState:UIControlStateNormal];
    [_remeberbutton addTarget:self action:@selector(remberPasswordAndName:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_remeberbutton];
    [_remeberbutton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomView.mas_bottom).offset(30);
        make.left.equalTo(self.view.mas_left).offset(30);
        make.width.mas_equalTo(120);
        make.height.mas_equalTo(20);
    }];
    UIButton *registerbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [registerbutton setTitle:@"新用户注册" forState:UIControlStateNormal];
    [registerbutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [registerbutton addTarget:self action:@selector(registerNewAcount) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerbutton];
    [registerbutton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomView.mas_bottom).offset(30);
        make.right.equalTo(self.view.mas_right).offset(-30);
        make.width.mas_equalTo(120);
        make.height.mas_equalTo(20);
    }];

    UIButton *loginbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginbutton.backgroundColor = [UIColor orangeColor];
    loginbutton.layer.cornerRadius = 30;
    loginbutton.layer.masksToBounds = YES;
    [loginbutton setTitle:@"登录" forState:UIControlStateNormal];
    [loginbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginbutton addTarget:self action:@selector(userLogin:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginbutton];
    [loginbutton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_remeberbutton.mas_bottom).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-30);
        make.left.equalTo(self.view.mas_left).offset(30);
        make.height.mas_equalTo(60);
    }];
    
}
/**
 *  注册新用户点击事件
 */
-(void)registerNewAcount{
    RegisterViewController *registerVc = [[RegisterViewController alloc] init];
    [self presentViewController:registerVc animated:YES completion:^{
        
    }];
}
/**
 *  记住密码点击事件
 *
 *  @param btn <#btn description#>
 */
-(void)remberPasswordAndName:(UIButton *)btn{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]) {
        [_remeberbutton setImage:[UIImage imageNamed:@"Login02"] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"phoneNumber"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];

    }else{
        [_remeberbutton setImage:[UIImage imageNamed:@"Login03"] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setObject:_userTextfiled.text forKey:@"phoneNumber"];
        [[NSUserDefaults standardUserDefaults] setObject:_passwordTextfiled.text forKey:@"passWord"];
    }

}
/**
 *  用户登录
 *
 *  @param btn
 */
-(void)userLogin:(UIButton *)btn{
    if ([_userTextfiled.text isEqual:@""] || [_passwordTextfiled.text isEqual:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"输入不能为空" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else{
        [self loginWithUsername:_userTextfiled.text andPassword:_passwordTextfiled.text];
    }
}
/**
 *  用户登录
 *
 *  @param userName 用户名
 *  @param password 密码
 */
-(void)loginWithUsername:(NSString *)userName andPassword:(NSString *)password{
     NSString *str = ServiceUrl@"/phoneUserApp/phoneUserLogin";
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSDictionary *dict = @{@"phone":userName,@"passWord":password};
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:str parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (dict[@"id"] == nil) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您输入的手机号或密码有误" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
            }else{
            [[NSUserDefaults standardUserDefaults] setObject:dict[@"id"] forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults] setObject:dict[@"name"] forKey:@"userName"];
            [[NSUserDefaults standardUserDefaults] setObject:dict[@"phone"] forKey:@"userphone"];
            [[NSUserDefaults standardUserDefaults] setObject:password forKey:@"userpassword"];
            [self dismissViewControllerAnimated:YES completion:^{
                NSLog(@"回到主页面了");
            }];}
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];

}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
